package logic

import (
	"context"
	"errors"
	"fmt"
	"good/goodrpc/goodrpc"
	"good/goodrpc/internal/svc"
	"good/models/mysql"
	"good/pkg"
	"math/rand"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *goodrpc.LoginRequest) (*goodrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	if user.Password != pkg.Md5str(in.Password) {
		return nil, errors.New("密码错误")
	} else {
		user := mysql.User{
			Account:   in.Account,
			Password:  pkg.Md5str(in.Password),
			HeadImage: "http://t1l21ie5x.hn-bkt.clouddn.com/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202025-07-21%20171936.png",
			NickName:  fmt.Sprintf("用户%d", rand.Intn(1000)),
		}
		mysql.DB.Debug().Create(&user)
	}

	return &goodrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
